package com.example.chapter1.exception;


import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request,Exception e){
            ModelAndView view = new ModelAndView();
            view.addObject("exception",e);
            view.addObject("url",request.getRequestURL());
            view.setViewName(DEFAULT_ERROR_VIEW);
            return view;
    }

    @ExceptionHandler(MyExpection.class)
    @ResponseBody
    public ErrorInfo<String> myErrorHandler(HttpServletRequest req,MyExpection e){
        ErrorInfo<String> r = new ErrorInfo<String>();
        r.setCode(ErrorInfo.ERROR);
        r.setMessage(e.getMessage());
        r.setUrl(req.getRequestURL().toString());
        r.setData("Some Data");
        return r;
    }
}
